import FileManager from '../FileSystem/file-stream-manager.js';
// import ImageProcessor from '../FileSystem/image-processor.js';
import { useMysql } from '../mysql/index.js';

// 初始化文件管理器
// const fileManager = new FileManager({
//   baseDir: 'public/uploads',
//   fileTypes: {
//     equipmentImg: {
//       subDir: 'equipmentImgs',
//       processor: new ImageProcessor() // 图片专用处理器
//     }
//   }
// });

// 为设备添加/更新图片
export const uploadEquipmentImage = async (req, res) => {
  // try {
  //   const { equipmentId } = req.params;
  //   if (!req.file) {
  //     return res.status(400).json({ error: '请上传图片文件' });
  //   }

  //   // 1. 保存文件
  //   const { filename, path: filePath } = await fileManager.saveFile(
  //     req.file, 
  //     'equipmentImg'
  //   );

  //   // 2. 更新数据库
  //   const updateSql = `UPDATE equipments SET ImagePath = ? WHERE EquipmentID = ?`;
  //   await useMysql(updateSql, [filename, equipmentId]);

  //   res.json({
  //     success: true,
  //     imageUrl: fileManager.getFileUrl(filename, { type: 'equipmentImg' })
  //   });
  // } catch (err) {
  //   res.status(500).json({ error: '图片上传失败' });
  // }
};

// 删除设备图片
export const deleteEquipmentImage = async (req, res) => {
  try {
    const { equipmentId } = req.params;
    
    // 1. 查询当前图片
    const [equipment] = await useMysql(
      'SELECT ImagePath FROM equipments WHERE EquipmentID = ?', 
      [equipmentId]
    );
    
    if (!equipment || !equipment.ImagePath) {
      return res.status(404).json({ error: '未找到图片记录' });
    }

    // 2. 删除物理文件
    const filePath = path.join(
      fileManager.baseDir,
      'equipmentImgs',
      equipment.ImagePath
    );
    await fileManager.deleteFile(filePath);

    // 3. 清空数据库记录
    await useMysql(
      'UPDATE equipments SET ImagePath = NULL WHERE EquipmentID = ?',
      [equipmentId]
    );

    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: '图片删除失败' });
  }
};

// 获取设备图片URL
export const getEquipmentImage = async (req, res) => {
  const { equipmentId } = req.params;
  const [equipment] = await useMysql(
    'SELECT ImagePath FROM equipments WHERE EquipmentID = ?',
    [equipmentId]
  );
  
  if (!equipment || !equipment.ImagePath) {
    return res.status(404).json({ error: '未找到图片' });
  }
  
  res.json({
    imageUrl: fileManager.getFileUrl(equipment.ImagePath, { 
      type: 'equipmentImg' 
    })
  });
};